import { onMounted, onUnmounted } from 'vue';

export const useInterval = (cb: () => void, time = 1000, immediate = true) => {
  let timer: any = null;

  const start = () => {
    timer = setInterval(() => {
      if (cb) cb();
    }, time);
  };

  const clear = () => {
    clearInterval(timer);
    timer = null;
  };

  onMounted(() => {
    if (immediate) start();
  });

  onUnmounted(() => {
    clear();
  });

  return { start, clear };
};
